package api

import (
	"cs/models"
	"cs/request"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetRoles(c *gin.Context) {
	roles, _ := models.GetRoles()

	c.JSON(http.StatusOK, gin.H{"status": "success", "roles": roles})
}

func AddRole(c *gin.Context) {
	var form request.AddRoleForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}

	if err := models.AddRole(form.Name, form.MenuIds); err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "message": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func UpdateRole(c *gin.Context) {
	var form request.UpdateRoleForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}

	if err := models.UpdateRole(form.ID, form.Name, form.MenuIds); err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "message": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func DeleteRole(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	if err := models.DelRole(id); err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "message": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}
